/**
 * 通用上传文件对话框
 * @author chaowangbang
 * @since 2012-1-1
 */

Ccay.Module.define("Ccay.Upload.Dialog",function(page,$S){	
	var uploadParameters;
	var uploaderComponent ;
	var title;
	var currFiles = {};
	
	//支持跨应用上传导入 要设置appServicePath属性
	function getFullServicePath(appServicePath,servicePath,uploadSupportInfo,uploadSupportUrl)
	{
		//支持自定义跨应用上传 pwx373895 2016-10-11
		if(appServicePath === true && uploadSupportInfo && uploadSupportUrl){
			appServicePath = "servlet/proxy/params/";
			if(servicePath.indexOf('services/ccay/upload/support/')>=0){
				//跨应用对应的上传类型信息、限制大小等。
				sp = servicePath.replace('services/ccay/upload/support/',uploadSupportInfo+'/');
			}
			else if(servicePath.indexOf('servlet/upload?')>=0){
				//跨应用对应的上传地址
				sp = servicePath.replace('servlet/upload?',uploadSupportUrl+'?');
			}
			return appServicePath+sp;
		}
		var idx = appServicePath.indexOf('/servlet/proxy/params/');
		var asp = appServicePath;
		var sp = servicePath;
       //判断是否为跨应用
		if(idx>0)
		{
			if(servicePath.indexOf('services/ccay/upload/support/')>=0)
			{
				sp = servicePath.replace('services/ccay/upload/support/','services_ccay_upload_support/');
			}
			else if(servicePath.indexOf('servlet/upload?')>=0)
			{
				sp = servicePath.replace('servlet/upload?','servlet_upload?');
			}
			else if(servicePath.indexOf('ccay/upload/support/plupload/plupload.flash.swf')>=0)
			{
				asp = appServicePath.substring(0,idx+1);
			}
			return asp+sp;
		}
		return appServicePath+servicePath;
	};
	
	/**
	 * 单选弹出框页面初始化
	 */
	page.init=function(uploadParam){
		var p = navigator.platform;
		if(p && p.indexOf("Linux")==0){
			setTimeout(function(){
				var div = $("div.plupload.html5").css("cursor","hand");
				var addBtn = $("a.plupload_button.plupload_add");
				div.parents(".ccay-dialog-body").css("overflow","hidden");
				if(div.length>0){
					div.css({top : addBtn.position().top+30});
				}
			},500);
		}else{
			setTimeout(function(){
				
				var div = $("div.plupload.html5").css("cursor","hand").unbind();
				$("div.plupload_container").removeAttr("title");
				var addBtn = $("a.plupload_button.plupload_add");
				div.parents(".ccay-dialog-body").css("overflow","hidden");
				if(div.length>0){
					div.css({top : addBtn.position().top });
				}
			},500);
		}
		
		title = document.title;
		setTimeout(function(){
				document.title = title;
		},10)
		$("#uploader").mousedown(function(){
			setTimeout(function(){
				document.title = title;
			},0)
			setTimeout(function(){
				document.title = title;
			},10)
			setTimeout(function(){
				document.title = title;
			},100)
		})
		uploadParameters = uploadParam;
		if(!uploadParameters.initCount){
			uploadParameters.initCount = 0;
		}
		
		uploadParameters.uploadedCount = 0 ;

		//如果需要批次号，并且批次号尚未生成
		if(uploadParam.needBatchId && !uploadParam.batchId){
			uploadParam.query = uploadParam.query + "&needBatchId=1";
		}

		var uploadSupportUrl="services/ccay/upload/support/{0}".formatURI(uploadParam.uploadType);

		//Ccay.Core.log(uploadParam); 
		Ccay.doGet(uploadParam.appServerPath?getFullServicePath(uploadParam.appServerPath,uploadSupportUrl,uploadParam.uploadSupportInfo,uploadParam.uploadSupportUrl):uploadSupportUrl,
				uploadParam.query,function(uploadSetting){			
			Ccay.Core.log("batch id got:" +uploadSetting.batchId );
			//Ccay.Core.log("batch id in param :" +uploadParam.batchId );
			
			if(!uploadParam.batchId && uploadSetting.batchId){
				//Ccay.Core.log("init batch id for this upload:" +uploadSetting.batchId) ;
				uploadParam.batchId = uploadSetting.batchId;
			}
			
			uploadParameters.maxFileCount = uploadSetting.maxFileCount;
			
			initComponent(uploadParam,uploadSetting);
		},function(textStatus, errorThrown){
			$S("#uploader").html($.i18n.prop("ccay.common.message.unknownError").encode());
		});
		
	};
	
	page.exit = function(){
		/**if(uploaderComponent){
			uploaderComponent.stop();
			Ccay.Core.log("Before stop uploader.Files to be removed from the queue: " + uploaderComponent.files.length);
			uploaderComponent.splice(0,uploaderComponent.files.length);			
			uploaderComponent.destroy();
		}
		delete uploadParameters;
		delete uploaderComponent;
		document.title=title;**/
		
		document.title = title;
		setTimeout(function(){
			document.title=title
		},10)
	}
	
	/**
	 *	转化格式
	 */
	function convert(fileTypes,fileTypeParam){
		// begin modify by zwx304259 sp21,根据参数控制浏览文件窗口显示"自定义文件"还是"所有文件"
		if(fileTypeParam){
			return [{title : "*", extensions : "*"}];
		}
		// end modify by zwx304259 sp21,根据参数控制浏览文件窗口显示"自定义文件"还是"所有文件"
		var p = navigator.platform;
		if(p && p.indexOf("Linux")==0){
			//var uploadType="doc,docx,xls,xlsx,xlsm,rar,zip";
			var types = fileTypes.join(",")
			return [{title : types, extensions : "*"}];
		}else{
			var types = fileTypes.join(",")
			return [{title : types, extensions : types}];
		}
	};
	
	function initComponent(uploadParam,uploadSetting){
		plupload.addI18n({
		    'Select files' : $.i18n.prop("ccay.upload.label.browse"),
		    'Add files to the upload queue and click the start button.' : $.i18n.prop("ccay.upload.label.browseAndStart"),
		    'Filename' : $.i18n.prop("ccay.upload.label.fileName"),
		    'Status' : $.i18n.prop("ccay.upload.label.status"),
		    'Size' : $.i18n.prop("ccay.upload.label.size"),
		    'Add Files' :$.i18n.prop("ccay.upload.label.browse"),
		    'Stop current upload' : $.i18n.prop("ccay.upload.label.stop"),
		    'Start uploading queue' : $.i18n.prop("ccay.upload.label.startQuere"),
		    'Drag files here.' : $.i18n.prop("ccay.upload.label.dragToHere") ,
		    'Start Upload': $.i18n.prop("ccay.upload.label.start"),
		    'Uploaded %d/%d files': $.i18n.prop("ccay.upload.label.uploaded"),
		    'Error: File too large: ': $.i18n.prop("ccay.upload.message.fileTooLarge"),
			'Error: Invalid file extension: ': $.i18n.prop("ccay.upload.message.fileTypeInvalid"),
			'File extension error.': $.i18n.prop("ccay.upload.message.fileTypeInvalid"),
			'File size error.': $.i18n.prop("ccay.upload.message.fileSizeError"),
			'File count error.': $.i18n.prop("ccay.upload.message.fileCountError"),
			'Using runtime:': $.i18n.prop("ccay.upload.message.usingRuntime")
		});
		
		//Ccay.Core.log("batch id in this upload:" +uploadParam.batchId);
		//Ccay.Core.log("uploadSetting.maxFileSize:" +uploadSetting.maxFileSize );
		
		var uploadUrl= "servlet/upload?ulType={0}&batchId={1}&".formatURI(uploadParam.uploadType, uploadParam.batchId) + uploadParam.query;
		//区分子应用
		if(uploadParam.currentContext){
			uploadUrl = "{0}/{1}".formatValue(uploadParam.currentContext,uploadUrl);
		}
		var flashUrl="ccay/upload/support/plupload/plupload.flash.swf";
		
		// begin modify by zwx304259 sp21,根据参数控制浏览文件窗口显示"自定义文件"还是"所有文件"
		var fileTypeParam = false;
				if (uploadParam.fileType && uploadParam.fileType.toUpperCase() == "ALL") {
					fileTypeParam = true;
				}
		// end modify by zwx304259 sp21,根据参数控制浏览文件窗口显示"自定义文件"还是"所有文件"
		//修复IE10下点击添加文件出现的问题。
		if($.browser.msie && $.browser.version.indexOf("10")==0){
			plupload.ua.webkit = true;
		}
		
		$S("#uploader").pluploadQueue({
			runtimes : 'html5,flash',
			//browse_button : 'pickfiles',
			url : uploadParam.appServerPath?getFullServicePath(uploadParam.appServerPath,uploadUrl,uploadParam.uploadSupportInfo,uploadParam.uploadSupportUrl):uploadUrl,
			max_file_size : uploadSetting.maxFileSize + 'b',
			//chunk_size : '2000mb', //暂不支持CHUNKED上传
			unique_names : true,			
			max_file_count: uploadSetting.maxFileCount,
			multi_selection:(uploadSetting.maxFileCount>1),
			filters : convert(uploadSetting.fileTypesAllowed,fileTypeParam),
			flash_swf_url : uploadParam.appServerPath?getFullServicePath(uploadParam.appServerPath,flashUrl,uploadParam.uploadSupportInfo,uploadParam.uploadSupportUrl):flashUrl,
			init:{
				 FileUploaded:fileUploaded,
				 UploadComplete:uploadComplete,
				 StateChanged:stateChanged,
				 QueueChanged:stateChanged,
				 FilesAdded:fileAdded,
				 FilesRemoved:filesRemoved,
				 UploadProgress:uploadProgress,
				 Error:fileError
			},
			preinit : {
				Init: function(up, info) {
					//修复IE8下面“共计”跟谷歌显示不一致问题。
					$S("#uploader_browse").text($.i18n.prop("ccay.upload.label.browse"));
					$S(".plupload_start").text($.i18n.prop("ccay.upload.label.start"));
		 			$(".plupload_file_size").prepend($.i18n.prop("ccay.upload.label.Total"));
					$("div.plupload_container").removeAttr("title");
					$S("#uploadMsg").text(
							$.i18n.prop("ccay.upload.label.allowed").formatValue(uploadSetting.fileTypesAllowed.join(","),
								uploadSetting.maxFileCount,Ccay.Format.toFileSize(uploadSetting.maxFileSize)));
					$S("#uploadMsgTip").show();
					
					if(info != null && "html5" !=  info.runtime) {							
							$S(".plupload_button").filter(".plupload_add").text($.i18n.prop("ccay.upload.label.browse"));
							$S(".plupload_button").filter(".plupload_start").text($.i18n.prop("ccay.upload.label.start")); 
					}
				}				
			}
		});
		
		//获得对象
		uploaderComponent = $S('#uploader').pluploadQueue();

		if($S("#uploader").children().length == 1){
			Ccay.UI.topBox($.i18n.prop("ccay.upload.message.noruntime"));
			setTimeout(function(){page.closeDialog()},1000);
			return ;
		}
		
		//对上传要求过滤类型为xlsm 时做处理
		if(uploadSetting.fileTypesAllowed.toString().indexOf("xlsm")!= -1){
           var div = $("div.plupload.html5"), input = div.find("input[type=file][accept]");
           if(input.length){
                input.attr("accept",input.attr("accept") + ",application/vnd.ms-excel.sheet.macroEnabled.12");
                //alert(input.attr("accept"));
           }
        }

		stateChanged(); 
	};
	function fileAdded(uploader,files){
		//Ccay.Core.log("Queue Size:" +  uploader.files.length);
		//Ccay.Core.log("max Count:" +uploadParameters.maxFileCount +" init count:" + uploadParameters.initCount  +" new files:" + files.length );
		var overMax = false;
		if(uploadParameters.initCount + uploader.files.length > uploadParameters.maxFileCount){
			overMax = true;
			for(var x=0;x < files.length ; x++){
				files[x].isOverMax = true;
				uploader.removeFile(files[x]);
			}
			Ccay.UI.showMessage($.i18n.prop("ccay.upload.message.overMaxCount").formatValue(uploadParameters.maxFileCount),"error");
		}
		var zeroFile = false, repeatFile = false , bool = false;
		for(var x=0;x < files.length ; x++){
			//清理掉已经在上传列表的文件，避免上传同名文件
			if(files[x] && currFiles[files[x].name]){
				uploader.removeFile(files[x]);
				repeatFile = true;
			}
			if(!files[x] || files[x].size == 0){
				uploader.removeFile(files[x]);
				zeroFile = true;
			}
			//文件添加
			if(uploadParameters.beforeAdd){
				var compare = uploadParameters.beforeAdd(files[x].name);
				if(compare === false){
					uploader.removeFile(files[x]);
					repeatFile = true;
				}
			}
		}
		//缓存已经在赏传列表的文件，避免上传同名文件，
		!overMax && $.each(files,function(){
			this.size && ( currFiles[this.name] = true );
		})
		if(repeatFile){
			Ccay.UI.topBox("ccay.upload.message.repeat")
		}
		if(zeroFile){
			Ccay.UI.showMessage($.i18n.prop("ccay.upload.message.filesZero"));
		}
	}
	
	function filesRemoved(uploader,files){
		//文件删除后，清理掉记录当前文件缓存
		
		if( files[0].isOverMax ){
			var bool = true;
			for(var item in currFiles){
				if(files[0].name == item){
					bool = false;
					break;
				}
			}
			bool &&  ( currFiles[files[0].name] = false );
			files[0].isOverMax = false;
		}else {
			currFiles[files[0].name] = false;
		}
		Ccay.Core.log("files removed:" +files.length);
	}
	
	function fileError(uploader,error){
		Ccay.Core.log("files upload error:" +error.message);
	}
	
	function stateChanged(){
		$S('#uploader > div.plupload').css('z-index','9999');	
		document.title=title;
		
/*		var goal = $S('#uploader > div.plupload')
			goal.css('z-index','9999'),
			ie_vision = goal.hasClass("flash") ? 8 : ($("#uploader div.plupload_buttons>a.plupload_add").length ? 10 : 0);	
		
			if(ie_vision){
				if(ie_vision == 8){
					setTimeout(function(){$S('#uploader > div.flash').css({'height':'28px','width':'80px'});},200);
				}else {
					setTimeout(function(){$("#uploader div.plupload_buttons>a.plupload_add").css({'padding-right':'4px'});},200);
				}
			}
		document.title=title;*/
	};

	function uploadComplete(uploader, files){
		$S(".plupload_buttons").show();
		$(".ccay-dialog.ccay-popup.modal").find(".ccay-dialog-closeimg").show();
		$(".ccay-dialog.ccay-popup.modal").find(".ccay-dialog-button").show();
		$(".plupload_file_action a").attr("onclick","return false");
		uploader.refresh();
		
		if(uploader.files.length ==0){
			return ;
		}
		
		if(uploadParameters.completeCallback){
			uploadParameters.completeCallback(files, uploadParameters.batchId, uploadParameters.userObject);
		}
		
		if(uploadParameters.closeDialog){
			page.closeDialog();			
		}		
	};

	
	function fileUploaded(uploader, file, serverResponse){
		var serverData = eval("(" + serverResponse.response +")");
		Ccay.Core.log("After Upload Complete: " + file.name);
		
		if(serverData && serverData.httpCode){
			Ccay.Core.log("Error: " + serverData.message);			
			
			if(serverData.message && serverData.message.indexOf("{") == 0){
				var msg = Ccay.DataHelper.toJson(serverData.message);
				Ccay.UI.showMessage($.i18n.prop("ccay.upload.message.failed").formatValue(file.name, msg.fieldErrors[0].messages));
			}else if(serverData.message && serverData.message.length >0){
				Ccay.UI.showMessage($.i18n.prop("ccay.upload.message.failed").formatValue(file.name,serverData.message),"error");
			} else {
				Ccay.UI.showMessage($.i18n.prop("ccay.upload.message.failed").formatValue(file.name,"Unknown."))
			}
			uploader.removeFile(file);
			
			return ;
		}
		
		if(uploadParameters.callback){
			uploadParameters.callback(file, serverData, uploadParameters.batchId, uploadParameters.userObject);
		} 
	}
	function uploadProgress(uploader, file){
			$(".ccay-dialog.ccay-popup.modal").find(".ccay-dialog-closeimg").hide();
			$(".ccay-dialog.ccay-popup.modal").find(".ccay-dialog-button").hide();
	}
});